package com.itheima.tanhua.interceptor;

import com.itheima.tanhua.exception.ConsumerException;
import com.itheima.tanhua.pojo.db.user;
import com.itheima.tanhua.until.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 芝士雪豹
 * @create 2022/9/20/20:16
 */
//拦截器
public class TanhuaInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String authorization = request.getHeader("Authorization");
        //判断token是否可用
        if (authorization==null || !JwtUtils.verifyToken(authorization)){
            throw new ConsumerException("登录已失效,请重新登录");
        }
        //获取token的声明和里面的数据
        //Claims=申明
        Claims claims = JwtUtils.getClaims(authorization);
        Integer id = (Integer) claims.get("id");
        String mobile = (String) claims.get("mobile");
        //创建user对象
        user user = new user();
        user.setId(id.longValue());
        user.setMobile(mobile);
        //将获取的数据加入 ThreadLocal中
        userHolder.set(user);
        return true;
    }
    //在校验 token以及获取晚数据后删除 ThreadLocal里的set() 你添加啥就删除啥
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        userHolder.remove();
    }
}
